package com.example.lklibrary.bi.exception;

import android.content.Context;
import android.content.Intent;

import com.example.lklibrary.bi.utils.LKSPUtil;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * 应用崩溃日志收集
 */
public class LKUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    private Context mContext;
    private boolean isRestart = false;

    public LKUncaughtExceptionHandler(Context context){
        this.mContext = context;
    }

    /**
     * @param context
     * @param flag 应用崩溃时是否重启
     */
    public LKUncaughtExceptionHandler(Context context, boolean flag){
    this.mContext = context;
        isRestart = flag;
    }
    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        //读取stacktrace信息
        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        throwable.printStackTrace(printWriter);
        String errorReport = result.toString();
        LKSPUtil.getInstance().putStringValue("errorInfo", errorReport);
        LKSPUtil.getInstance().putStringValue("errorTime", String.valueOf(System.currentTimeMillis()));
        if(isRestart) {
            restartApplication();
        }
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    private void restartApplication() {
        final Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mContext.startActivity(intent);
    }
}
